package netWork;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class UdpEchoServer {
    //服务器
    private DatagramSocket socket = null;
    //服务器端口号
    private static final int port = 8888;
    public static void main(String[] args) throws IOException {
        //创建socket对象
        UdpEchoServer udpEchoServer = new UdpEchoServer(port);
        udpEchoServer.start();
    }
    //绑定一个端口不一定100%成功,如果某个端口已经被别的进程占用了,就会报错
    //同一主机,同一端口,同一时刻只能被一个进程绑定
    public UdpEchoServer (int port) throws SocketException {
        //创建一个服务器,指定端口号为port
        socket = new DatagramSocket(port);
    }
    public void start() throws IOException {
        //启动服务器的主逻辑
        System.out.println("服务器启动!!!");
        while (true){
            //构建空饭盒
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096],4096);
            //读取请求并解析
            //将网卡中读取到的数据传输到数据包中
            socket.receive(requestPacket);
            String request = new String(requestPacket.getData(),0,requestPacket.getLength());
            //根据请求计算相应
            String response =  process(request);
            //把响应返回客服端
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(StandardCharsets.UTF_8),
                    response.getBytes(StandardCharsets.UTF_8).length,requestPacket.getSocketAddress());
            socket.send(responsePacket);
            System.out.printf("[%s:%d] req: %s ,resp %s\n",requestPacket.getAddress().toString(),requestPacket.getPort(),request,response);

        }

    }

    private String process(String request) {

        return request+"我喜欢你";
    }


}
